import { login, register, userInfo } from "../../api/login";
import { setCookie, getCookie, removeCookie } from "../../utils/auth";

const state = {
  token: getCookie('token'),
  userInfo: {},
  logo: '',
  nowReviewId: ''
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USERINFO: (state, userInfo) => {
    state.userInfo = userInfo
  },
  SET_LOGO: (state, logo) => {
    state.logo = logo
  },
  SET_NOWREVIEWID: (state, nowReviewId) => {
    state.nowReviewId = nowReviewId
  }
}

const actions = {
  setLogo({ commit }, logo) {
    commit('SET_LOGO', logo)
  },
  setReviewId({ commit }, nowReviewId) {
    commit('SET_NOWREVIEWID', nowReviewId)
  },
  // user login
  login({ commit }, formObj) {
    return new Promise((resolve, reject) => {
      login(formObj).then(response => {
        const { data } = response
        const token = data.token
        commit('SET_TOKEN', token)
        setCookie("token", token);
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  // user register
  register({ commit }, formObj) {
    return new Promise((resolve, reject) => {
      register(formObj).then(() => {
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      userInfo({token: state.token}).then(response => {
        const { data } = response

        if (!data) {
          reject('Verification failed, please Login again.')
        }

        commit('SET_USERINFO', data)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },
  // user logout
  logout({ commit }) {
    return new Promise((resolve) => {
      commit('SET_TOKEN', '')
      commit('SET_USERINFO', {})
      removeCookie('token')

      resolve()
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      removeCookie('token')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
